﻿#include "WRWorkObjectCollection.h"

#include "WRWorkModule.h"
#include "WRWorkObject.h"

#include <QList>
#include <QHash>


//初始化工作对象集合。
WRWorkObjectCollection::WRWorkObjectCollection(const WRArray<WRWorkObject*>& objects)
{
    if (objects.count()>0)
    {
        typedef QList<WRWorkObject*> List;
        typedef QHash<QUuid, List> Hash;

        Hash hash;
        for(WRu i = 0; i < objects.count(); ++i)
        {
            WRWorkObject* object = objects[i];
            WRType* type = object->type();
            while(type)
            {
                auto iter = hash.find(type->uuid());
                if (iter == hash.end())
                {
                    iter=hash.insert(type->uuid(), List());
                }
                iter.value().append(object);
                type = type->base();
            }
        }

        WRArray<Entry> array(hash.count() + 1);
        array[0] = Entry(QUuid(), objects);
        WRu index = 1;
        for(auto iter = hash.begin(); iter != hash.end(); iter++, ++index)
        {
            array[index] = Entry(iter.key(), WRArray<WRWorkObject*>(iter.value()));
        }
        m_data = objects;
        m_array = array;
    }
}

//初始化工作对象集合。
WRWorkObjectCollection::WRWorkObjectCollection(const WRArray<WRWorkModule*>& modules)
{
    typedef QList<WRWorkObject*> List;
    typedef QHash<QUuid, List> Hash;

    Hash hash;
    List allList;
    for(WRu i = 0; i < modules.count(); ++i)
    {
        auto& objects = modules[i]->objects();
        for(WR32u j = 0; j < objects.count(); ++j)
        {
            WRWorkObject* object = objects[j];
            allList.append(object);
            WRType* type = object->type();
            while(type)
            {
                auto iter = hash.find(type->uuid());
                if (iter == hash.end())
                {
                    iter=hash.insert(type->uuid(), List());
                }
                iter.value().append(object);
                type = type->base();
            }
        }
    }
    if (hash.count())
    {
        WRArray<Entry> array(hash.count() + 1);
        array[0] = Entry(QUuid(), WRArray<WRWorkObject*>(allList));
        WRu index = 1;
        for(auto iter = hash.begin(); iter != hash.end(); iter++, ++index)
        {
            array[index] = Entry(iter.key(), WRArray<WRWorkObject*>(iter.value()));
        }
        m_data = array[0].data();
        m_array = array;
    }
}

//获取指定类型的对象集合。
const WRArray<WRWorkObject*>& WRWorkObjectCollection::filter(const QUuid& tuid) const
{
    for(WRu i = 0, l = m_array.count(); i < l; ++i)
    {
        const Entry& entry = m_array[i];
        if (entry.uuid() == tuid)
        {
            return entry.data();
        }
    }
    return WRArray<WRWorkObject*>::empty();
}
